<?php

App::uses('AppController', 'Controller');

class InvoicesController extends AppController {
    
    public $pageTitle = "Fakture";
    
    public $paginate = array(
        'limit' => ITEMS_PER_PAGE,
        'conditions' => array(
            'Invoice.storno !=' => 1
        ),
        'group' => 'Invoice.id'
    );
    
    public $uses = array('Invoice', 'Settings');
    
    public function index() {
        $filter = $this->parseFilterData('Invoice');
        $selectedTab = 'Aktivne';
        
        $storno = (int)@$this->params->query['storno'];
        if ($storno) {
            $selectedTab = 'Stornirane';
            $this->paginate['conditions'] = array('Invoice.storno'=>1);
        }
        
        $this->paginate['order'] = "{$filter->sortBy} {$filter->sortDir}";
        $invoices = $this->paginate('Invoice', $filter->conditions);
        
        $this->set(compact('invoices', 'selectedTab'));
        $this->setFilterData($filter);
    }
    
    public function create() {
        $data = $this->Invoice->create();
        
        $campaign = @$this->params->query['campaign'];
        if (! empty($campaign)) {
            $campaign = $this->Invoice->Campaign->findById($campaign);
            $campaign['Campaign']['Location'] = $campaign['Location'];
            $campaign['Campaign']['Client'] = $campaign['Client'];
            $data['Campaign'] = Set::extract('Campaign', $campaign);
            
            // load Services
            $data['InvoiceService'] = array();
            foreach ($campaign['Location'] as $loc) {
                $location = $this->Invoice->Campaign->Location->findById($loc['id']);
                $ads = Set::extract('{n}.name', $location['AdType']);
                
                $lbl = count($ads)>1 ? 'reklame' : 'reklama';
                $data['InvoiceService'][] = array(
                    'service' => implode(", ", array_unique($ads)) . ' ' . $lbl . ' na lokaciji ' . $loc['name']
                );
            }
        }
                
        $this->set(compact('data', 'campaign'));
        $this->render('form');
    }
    
    public function edit($id) {
        $data = $this->Invoice->findById($id);
        $c = $this->Invoice->Campaign->findById($data['Campaign']['id']);
        $data['Campaign']['Location'] = $c['Location'];
        $data['Campaign']['Client'] = $c['Client'];
        
        $this->set('data', $data);
        $this->render('form');
    }
    
    public function save() {
        $data = $this->data;
        if (! empty($data)) {
            $this->Invoice->create($data);
            
            if (! $this->Invoice->validates()) {
                $this->set('data', $data);
                $this->setFlash('Uneti podaci nisu validni.');
                return $this->render('form');
            }
            
            $this->Invoice->deleteRelatedData();
            if (! $this->Invoice->saveAll($data)) {
                $this->set('data', $data);
                $this->setFlash('Čuvanje nije uspelo.');
                return $this->render('form');
            }

            $this->setFlash('Faktura je uspešno sačuvana.', 'ok');
            $this->redirect('edit/' . $this->Invoice->id);
        }
        
        $this->redirect('index');
    }
    
    public function storno($id, $value=1) {
        
        $value = (int)$value ? 1 : 0;
        $message = $value ? 'Faktura je stornirana' : 'Faktura je od-stornirana.';
        
        if ($this->Invoice->save(array(
                'id'     => $id,
                'storno' => $value
            ))) {
            $this->setFlash($message, 'ok');
        }else{
            $this->setFlash('Greška pri čuvanju fakture.');
        }
        $this->redirect('index/?storno=' . ($value ? 0 : 1));
    }
	
	public function remove($id) {
		if ($this->Invoice->delete($id)) {
			$this->setFlash('Faktura je obrisana.', 'ok');
		} else {
			$this->setFlash('Greška pri brisanju fakture.');
		}
		
		$this->redirect('index');
	}
    
    public function search() {
        $this->autoRender = false;
        
        $kword = $this->params->query['term'];
        $invoices = array();
        $res = $this->Invoice->find('all', array(
            'fields'     => array('Invoice.id', 'Invoice.number'),
            'conditions' => array('OR' => array(
                'Invoice.number LIKE'  => "%{$kword}%"
            ))
        ));
        if ($res) {
            foreach ($res as $row) {
                $invoices[] = array(
                    'id'    => $row['Invoice']['id'],
                    'label' => $row['Invoice']['number']
                );
            }
        }
        
        echo json_encode($invoices);
    }
    
    public function pdf($id) {
        $this->set('data', $this->Invoice->find('first', array(
            'conditions' => array( 'Invoice.id' => $id),
            'recursive'  => 3
        )));
        $this->set('settings', $this->Settings->load());
        
        $this->layout = 'blank';
    }
    
    public function pdf_save($id) {
        
        $form = $this->data['service'];
        $data = $this->Invoice->find('first', array(
            'conditions' => array( 'Invoice.id' => $id),
            'recursive'  => 2
        ));
        
        $this->set(compact('data', 'form'));
        $this->layout = 'pdf';
    }
    
}
